package org.javaboy.websocket_demo.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

@Configuration
//开启消息代理
@EnableWebSocketMessageBroker
public class WsConfig implements WebSocketMessageBrokerConfigurer {
    /**
     * 这个地方相当于配置 ws 的连接点
     * @param registry
     */
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry
                //配置连接点，浏览器将来就发送消息给这个端点
                .addEndpoint("/myws/ep")
                //设置 websocket 链接从哪里发送来的
                .setAllowedOrigins("http://localhost:8080")
                //前端支持 sockjs 库
                .withSockJS();
    }

    /**
     * 配置消息代理，哪些位置的消息，将来要通过 Spring 进行代理
     * @param registry
     */
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        //将来发消息的时候，如果消息发送目标地址是 /topic 或者 /queue 开始的，则消息转交给 Spring 去代理
        registry.enableSimpleBroker("/topic", "/queue");
        registry.setApplicationDestinationPrefixes("/app");
    }
}
